package com.example.redis.connect;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * Jedis API类
 * 创建时间：2022/4/5 21:39
 *
 * @author gejin
 */
public class TestMulti {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        // 测试连接是否成功
        System.out.println(jedis.ping());
        jedis.flushDB();
        // 向Redis 服务器中添加两个数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "jinjin");
        jsonObject.put("password", "123456");
        String result = jsonObject.toJSONString();
        // 开启事务
        Transaction multi = jedis.multi();
        try {
            multi.set("user1", result);
            multi.set("user2", result);
            // 弄一个异常在这儿
            int num = 1 / 0;
            multi.exec();
        } catch (Exception e) {
            System.out.println("存在异常：" + e);
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            // 关闭redis
            multi.close();
        }

    }

}
